package com.ch.clinking.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.ch.clinking.BroadcastReceiver.DownloadCompleteReceiver;
import com.ch.clinking.BuildConfig;
import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.Dao.RememberPasswordDao;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.DoCallBack;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.bean.RememberPassword;
import com.ch.clinking.bean.Shop;
import com.ch.clinking.bean.User;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SplashActivity extends AppCompatActivity {

    private RememberPasswordDao rememberPasswordDao;
    private ClinkingApplication app;

    private DownloadCompleteReceiver receiver;

    private long downloadId;
    private ProgressBar progressBar;
    private TextView percentageText;

    private String latestVersion;

    private boolean update = true;

    private static final int REQUEST_CODE_PERMISSIONS = 100;

    private String packageName;


    private BroadcastReceiver dataLoadedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 数据加载完成广播收到，关闭启动屏
            finish();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(dataLoadedReceiver);
        unregisterReceiver(onComplete);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        // 初始化 ProgressBar 和 TextView
   //     progressBar = findViewById(R.id.progressBar);
     //   percentageText = findViewById(R.id.percentageText);




        registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
//        receiver = new DownloadCompleteReceiver();
//        IntentFilter filter = new IntentFilter("android.intent.action.DOWNLOAD_COMPLETE");
//        registerReceiver(receiver, filter);


        checkForUpdate(); // 在Activity启动时检查更新
   //     requestPermissions();
//        into();


        app = ClinkingApplication.getInstance();




    }

    private void into() {
        // 检查用户是否已经登录
        SharedPreferences preferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
        boolean isLoggedIn = preferences.getBoolean("is_logged_in", false);

        if (isLoggedIn) {
            // 用户已经登录，跳转到主页面

            rememberPasswordDao = ClinkingApplication.getInstance().getDatabase().rememberPasswordDao();
            RememberPassword latestUser = rememberPasswordDao.selectLatestUser();

            //获取用户
            HashMap<String, String> selectUser = new HashMap<>();
            selectUser.put("account",latestUser.getAccount());
            OkHttpUtil.getInstance().doPostForm("/user/selectByAccount", new DoCallBack() {
                @Override
                public void onSuccess(String result) {

                    //App全局User变量
                    app.user = new Gson().fromJson(result, User.class);

                    // 查询管理的店铺列表
                    HashMap<String, String> selectShopList = new HashMap<>();
                    selectShopList.put("account",app.user.getAccount());
                    OkHttpUtil.getInstance().doPostForm("/shop/selectShopListByUserId", new DoCallBack() {
                        @Override
                        public void onSuccess(String result) {

                            Shop[] shopList = new Gson().fromJson(result, Shop[].class);
                            app.shopList = Arrays.asList(shopList);

                            // 注册广播接收器
                            LocalBroadcastManager.getInstance(SplashActivity.this).registerReceiver(dataLoadedReceiver, new IntentFilter("com.example.DATA_LOADED"));
                            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                            startActivity(intent);

//                            // 延迟执行
//                            new Handler().postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    // 启动主页面
//                                    Intent intent = new Intent(SplashActivity.this, MainActivity.class);
//                                    startActivity(intent);
//                                    // 关闭启动屏
//                                    finish();
//                                }
//                            }, 200); // 延迟 0.2 秒


                        }

                        @Override
                        public void onError(Exception e) {
                            Toast.makeText(SplashActivity.this, "网络错误", Toast.LENGTH_SHORT).show();

                            // 延迟执行
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    // 启动主页面
                                    Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
                                    startActivity(intent);
                                    // 关闭启动屏
                                    finish();
                                }
                            }, 200); // 延迟 0.2 秒

                        }
                    },selectShopList);

                }

                @Override
                public void onError(Exception e) {
                    Toast.makeText(SplashActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                }
            },selectUser);


        } else {
            // 用户未登录，跳转到登录页面


            // 延迟执行
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // 启动主页面
                    Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
                    startActivity(intent);
                    // 关闭启动屏
                    finish();
                }
            }, 200); // 延迟 0.2 秒

        }
    }

    private void checkForUpdate() {
        // 假设你有一个 API 可以返回最新版本的信息
        String latestVersionUrl = "http://8.146.200.102:5000/version";

        // 发起网络请求检查版本号（可以使用 Retrofit、OkHttp 等网络库）
        // 示例使用OkHttp
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(latestVersionUrl).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 处理请求失败的情况
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 解析返回的 JSON 数据
                    String jsonResponse = response.body().string();
                    Log.e("jsonResponse", jsonResponse);

                    try {
                        JSONObject jsonObject = new JSONObject(jsonResponse);
                        latestVersion = jsonObject.getString("versionName");
                        final String downloadUrl = jsonObject.getString("apkUrl");
                        packageName = "/Clinking"+"-"+latestVersion+".apk";

                        // 比较当前版本号和服务器的版本号
                        if (isUpdateAvailable(latestVersion)) {
                            // 在主线程中显示更新对话框
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showUpdateDialog(downloadUrl);
                                    Log.e("apkUrl", downloadUrl);
                                }
                            });
                        }else {

                            into();

                        }
                    } catch (JSONException e) {
                        Log.e("UpdateCheck", "JSON parsing error", e);
                    }
                } else {
                    Log.e("UpdateCheck", "Server returned an error");
                }
            }
        });
    }

    private boolean isUpdateAvailable(String latestVersion) {
        String currentVersion = BuildConfig.VERSION_NAME;
        return !currentVersion.equals(latestVersion);
    }

    private BroadcastReceiver onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            // 通过 Intent 安装 APK

            String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + packageName;

            // 延迟 1 秒后检查文件是否存在并安装
            new Handler().postDelayed(() -> {
                File file = new File(filePath);
                if (file.exists()) {
                    installApk(filePath);
                } else {
                    // 处理文件不存在的情况
                    Log.e("InstallAPK", "文件不存在，无法安装");
                }
            }, 1000);  // 延迟 1 秒
        }
    };

//    private void installApk(String filePath) {
//        File file = new File(filePath);
//        Log.d("InstallAPKInstallAPK", "文件路径: " + filePath);
//        Log.d("InstallAPKInstallAPK", "文件存在: " + file.exists());
//
//        if (file.exists()) {
//            // 获取APK的Uri
//            Uri apkUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", file);
//            Log.d("InstallAPKInstallAPK", "apkUri: " + apkUri);
//            Log.d("InstallAPKInstallAPK", "APK URI: " + apkUri.toString());
//
//            // 使用AppUtils安装应用
//            try {
//                AppUtils.installApp(apkUri); // 传入Uri类型的参数
//            } catch (Exception e) {
//                Log.e("InstallAPKInstallAPK", "安装过程中发生错误: " + e.getMessage());
//                Toast.makeText(this, "安装失败", Toast.LENGTH_SHORT).show();
//            }
//        } else {
//            Log.e("InstallAPKInstallAPK", "文件不存在，无法安装");
//            Toast.makeText(this, "安装包未找到", Toast.LENGTH_SHORT).show();
//        }
//    }



    private void installApk(String filePath) {
//        File file = new File(filePath);
        String pa = "/storage/emulated/0/Download/mtxx_843939247.apk";
        File file = new File(pa);
        Log.d("InstallAPKInstallAPK", "文件路径: " + filePath);
        Log.d("InstallAPKInstallAPK", "文件存在: " + file.exists());

        if (file.exists()) {

            // 创建Intent
            Uri apkUri;
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            intent.addCategory("android.intent.category.DEFAULT");

            // 根据 Android 版本选择不同的 URI 处理方式
            if (Build.VERSION.SDK_INT >= 24) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                apkUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", file);
            } else {
                apkUri = Uri.fromFile(file);
            }
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");

            // 获取APK的Uri
//            Uri apkUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", file);
            Log.d("InstallAPKInstallAPK", "apkUri: " + apkUri);
            Log.d("InstallAPKInstallAPK", "APK URI: " + apkUri.toString());
            Log.d("InstallAPKInstallAPK", "APK URI: " + apkUri.getPath());

            // 添加启动标志，确保安装界面是在新任务中启动的
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // 启动安装活动
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Log.e("InstallAPKInstallAPK", "没有找到安装应用的活动: " + e.getMessage());
                Toast.makeText(this, "没有找到安装应用的活动", Toast.LENGTH_SHORT).show();
            }
        } else {
            Log.e("InstallAPKInstallAPK", "文件不存在，无法安装");
            Toast.makeText(this, "安装包未找到", Toast.LENGTH_SHORT).show();
        }
    }




    private void showUpdateDialog(String downloadUrl) {
        new AlertDialog.Builder(this)
                .setTitle("Update Available")
                .setMessage("A new version of the app is available. Would you like to update now?")
                .setPositiveButton("Yes", (dialog, which) -> downloadApk(downloadUrl))
                .setNegativeButton("No", (dialog, which) -> into())
                .show();
    }

    private void downloadApk(String downloadUrl) {



        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
        request.setTitle("Downloading Update");
        request.setDescription("Downloading the latest version of the app.");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, packageName);

        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        downloadId = manager.enqueue(request);

        // 启动检查下载进度的方法
        checkDownloadProgress(downloadId);
    }

    private void checkDownloadProgress(long downloadId) {
        new Thread(() -> {
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            boolean downloading = true;
            while (downloading) {
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                Cursor cursor = manager.query(query);
                if (cursor.moveToFirst()) {
                    @SuppressLint("Range") int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    if (status == DownloadManager.STATUS_SUCCESSFUL) {
                        // 下载完成
                        runOnUiThread(() -> percentageText.setText("100%"));
                        downloading = false;
                    } else if (status == DownloadManager.STATUS_FAILED) {
                        // 下载失败
                        runOnUiThread(() -> percentageText.setText("Failed"));
                        downloading = false;
                    } else {
                        // 下载中，获取进度
                        @SuppressLint("Range") int bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        @SuppressLint("Range") int bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                        final int progress = (int) ((bytesDownloaded * 100L) / bytesTotal);

                        // 更新 UI 线程
                        runOnUiThread(() -> {
                            if (progressBar != null) {
                                progressBar.setProgress(progress);
                            }
                            if (percentageText != null) {
                                percentageText.setText(progress + "%");
                            }
                        });
                    }
                }
                cursor.close();
                try {
                    Thread.sleep(1000); // 每秒检查一次进度
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void requestPermissions() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!getPackageManager().canRequestPackageInstalls()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 1234);
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查是否已经拥有所需权限
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                // 请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_PERMISSIONS);
            } else {
                // 权限已被授予，执行相关操作
                checkForUpdate();
            }
        } else {
            // 设备版本低于 Android 6.0，不需要请求权限
            checkForUpdate();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已被授予
                checkForUpdate();
            } else {
                // 权限被拒绝
                Toast.makeText(this, "下载和安装更新需要权限", Toast.LENGTH_SHORT).show();
            }
        }
    }





}
